/**
 * @author  : ZhiBing.Li
 * @date    : 2013-10-15下午01:46:51
 */
package flexcomm.controls.checkboxdg
{
	import flash.events.Event;
	
	import spark.components.CheckBox;
	import spark.components.Grid;
	import spark.components.gridClasses.GridItemRenderer;
	import spark.components.gridClasses.GridLayer;
	
	public class CheckBoxGrid extends GridItemRenderer
	{
		private var _checkBox:CheckBox;
		
		public function CheckBoxGrid()
		{
			super();
		}
		
		override protected function createChildren():void
		{
			super.createChildren();
			
			//初始化复选框组件
			if(!_checkBox)
			{
				_checkBox = new CheckBox();
				_checkBox.addEventListener(Event.CHANGE,onChangeHandler);
				this.addElement(_checkBox);
			}
			
			if(owner is GridLayer)
			{
				//监听表格事件
				var gridLayer:GridLayer = GridLayer(this.owner);
				var grid:Grid = Grid(gridLayer.owner);
				CheckBoxDataGrid(grid.dataGrid).addEventListener(CheckBoxEvent.CHANGE,onCheckBoxChangeHandler);
			}
		}
		
		override protected function updateDisplayList(w:Number, h:Number):void
		{
			super.updateDisplayList(w,h);
			
			//设置checkBox的X
			var ckbX:Number = (w - _checkBox.width) / 2;
			//设置checkBox的Y
			var ckbY:Number = (h - _checkBox.height) / 2;
			//设置checkBox的坐标及大小
			_checkBox.move(ckbX,ckbY);
		}
		
		override public function set data(value:Object):void
		{
			if(value == null)
				return;
			
			super.data = value;
			
			if(data.hasOwnProperty('selected'))
			{
				//如果数据源有selected属性
				_checkBox.selected = Boolean(data['selected']);
				//派发复选款选中状态事件
				_checkBox.dispatchEvent(new Event(Event.CHANGE));
			}
		}
		
		//组件改变状态处理事件
		protected function onChangeHandler(event:Event):void
		{
			var dg:CheckBoxDataGrid = CheckBoxDataGrid(this.owner);
			
			if(_checkBox.selected)
			{
				dg.addToSelected(data);
			}
			else
			{
				dg.removeToSelected(data);
			}
		}
		
		//处理全选状态事件
		protected function onCheckBoxChangeHandler(event:CheckBoxEvent):void
		{
			var selected:Boolean = event.selected;
			_checkBox.selected = selected;
			_checkBox.dispatchEvent(new Event(Event.CHANGE));
		}
	}
}